package com.ophiux.cs.application.appraise.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ophiux.cs.application.appraise.dto.AppraiseOrderRequest;
import com.ophiux.cs.application.appraise.dto.AppraiseOrderResponse;
import com.ophiux.cs.application.appraise.service.IAppraiseAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.appraise.model.entity.CsUserAppraises;
import com.ophiux.cs.domain.appraise.model.valueobj.Appraise_ConsultOrder;
import com.ophiux.cs.domain.appraise.remote.IAppraise_ConsultOrderRemoteService;
import com.ophiux.cs.domain.appraise.remote.IAppraise_UserRemoteService;
import com.ophiux.cs.domain.appraise.repositories.IAppraiseRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AppraiseAppService implements IAppraiseAppService {
	@Autowired
	IAppraiseRepository appraiseRepository;
	@Autowired
	IAppraise_UserRemoteService appraise_UserRemoteService;
	@Autowired
	IAppraise_ConsultOrderRemoteService appraise_ConsultOrderRemoteService;
	
	@Override
	@Transactional
	public Result<AppraiseOrderResponse> appraiseOrder(AppraiseOrderRequest dto) {
		try {
			if(!dto.isParamValid()) {
				return Result.fail(ResultEnum.requestParamFail);
			}
			
			CsUserAppraises obj = new CsUserAppraises(dto.getUSER_ID(),dto.getDOCTOR_ID(),dto.getRECORD_ID());
			obj.setMARK(dto.getMARK());
			obj.setCONTENT(dto.getCONTENT());
			obj.setCS_EFFECT(dto.getCS_EFFECT());
		
			//1.判断用户是否存在
			boolean UserIsNoExist = appraise_UserRemoteService.getUserIsExist(dto.getUSER_ID());
			if(!UserIsNoExist) {
				return Result.fail(ResultEnum.NotFundUser);
			}
			
			//2.判断订单是否存在
			Appraise_ConsultOrder order = appraise_ConsultOrderRemoteService.getConsultOrderByRecordId(dto.getRECORD_ID());
			if(order==null) {
				return Result.fail(ResultEnum.NotFoundConsultRecord);
			}
			
			obj.addPatientInfo(order.getPATIENT_NAME(), order.getSEX(), order.getPHONE());
			//3.保存评价
			appraiseRepository.save(obj);
			
			//4.修改订单评价状态
			appraise_ConsultOrderRemoteService.updateConsultOrderAppraiseStatus(dto.getRECORD_ID());
			
		} catch (Exception e) {
			log.info("程序异常：",e);
			e.printStackTrace();
			return Result.fail(ResultEnum.requestException);
		}
		return Result.success();
	}
	
}
